/* 
*@module: login
*@author: 陈刚
*/

const UserModel = require('../../models/user/login.js')
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const aesDecrypt = require('../../utils/aes').aesDecrypt
const secret = 'shu-project'
const key = 'shu'

class User_Controller {

	/**
	 * 登陆，成功的话给用户分发token
	 * @param ctx req_userInfo    用户信息 --包含用户名和aes加密的用户密码
	 *
	 * @memberof User_Controller
	 */
	static async login(ctx) {
		const req_userInfo = ctx.request.body
		console.log("username", req_userInfo.username)
		let userInfo = await UserModel.login(req_userInfo.username)
		console.log("userInfo", userInfo)		
		if (userInfo) {
			let password = aesDecrypt(req_userInfo.password, key) //解密
			if (userInfo.password == password) {
				const userToken = {
					id: userInfo.id,
					username: userInfo.username,
					roles: userInfo.roles,
					project_owner: userInfo.project_owner,
					avatar: userInfo.avatar
				}

				// 签发token
				const token = jwt.sign(userToken, secret, { expiresIn: 60*60*3 })

				ctx.body = {
					code: 200,
					success: true,
					token: token,
					msg: '获取成功'
				}
			} else {
				ctx.body = {
					code: 412,
					success: false,
					msg: '密码不正确'
				}
			}
		} else {
			ctx.body = {
				code: 413,
				success: false,
				msg: '用户不存在'
			}
		}
	}

	/**
	 * 根据请求头携带的token获取对应的用户信息
	 * @param ctx token    分发的用户token
	 * 
	 * @memberof User_Controller
	 */
	static async getUserInfo(ctx) {
		const token = ctx.header['shu-token']

		if (token) {
			try {
				let playload = await jwt.verify(token, secret)
				console.log('playload', playload)
				let user = {
					name: playload.username,
					roles: [playload.roles],
					avatar: playload.avatar
				}
				ctx.body = {
					code: 200,
					success: true,
					res: user,
					msg: '获取成功'
				}
			} catch{
				ctx.body = {
					code: 50014,
					success: true,
					res: user,
					msg: '获取成功'
				}
			}

		} else {
			ctx.body = {
				success: false,
				msg: '获取token失败'
			}
		}

	}

}

module.exports = User_Controller
